//
//  LoginView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI

struct LoginView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    @State private var phoneNumber = ""
    @State private var verificationCode = ""
    @State private var inviteCode = ""
    @State private var isCodeSent = false
    @State private var showingAlert = false
    @State private var alertMessage = ""
    @State private var isLoading = false
    @State private var countdown = 60
    @State private var canResendCode = true
    @State private var timer: Timer?
    @State private var showingTerms = false
    @State private var showingPrivacy = false
    @State private var showingLanguageSelector = false
    @State private var showingBiometricPrompt = false
    @State private var biometricLoginAttempted = false
    @FocusState private var phoneNumberFocused: Bool
    @FocusState private var verificationCodeFocused: Bool
    @FocusState private var inviteCodeFocused: Bool
    @StateObject private var interactionManager = LoginInteractionManager()
    // 诊断相关状态变量
    @State private var diagnosticTapCount = 0
    @State private var showDiagnostic = false
    @State private var showPerformanceTest = false
    
    var body: some View {
        ZStack {
            // 背景图片 - 确保覆盖整个屏幕
            Image("LoginBackground")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .ignoresSafeArea(.all)
            
            // 添加半透明遮罩以确保文字清晰可见
            Rectangle()
                .fill(Color.black.opacity(0.3))
                .ignoresSafeArea(.all)
                .onTapGesture {
                    if LoginUIConfig.enableTapToDismissKeyboard {
                        interactionManager.dismissKeyboard()
                        phoneNumberFocused = false
                        verificationCodeFocused = false
                        inviteCodeFocused = false
                    }
                }
            
            GeometryReader { geometry in
                let screenHeight = geometry.size.height
                let screenWidth = geometry.size.width
                let isLargeScreen = screenHeight > 800
                
                ScrollView(.vertical, showsIndicators: false) {
                    VStack(spacing: 0) {
                        Spacer(minLength: screenHeight * 0.08)
                        
                        // Logo区域 - 响应式调整
                        VStack(spacing: isLargeScreen ? 20 : 15) {
                            Image("Logo")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(height: isLargeScreen ? 140 : 120)
                                .shadow(color: Color.black.opacity(0.3), radius: 10, x: 0, y: 5)
                        }
                        .padding(.bottom, screenHeight * 0.03)
                        
                        // 三语Slogan - 响应式调整
                        VStack(spacing: isLargeScreen ? 12 : 10) {
                            Text(AppStrings.Login.healthyKoreanFastFood)
                                .font(isLargeScreen ? .title : .title2)
                                .fontWeight(.semibold)
                                .foregroundColor(.white)
                            
                            Text(AppStrings.Login.powerUpSlogan)
                                .font(isLargeScreen ? .title2 : .headline)
                                .foregroundColor(.white)
                            
                            Text(AppStrings.Login.koreanSlogan)
                                .font(isLargeScreen ? .headline : .subheadline)
                                .foregroundColor(.white)
                        }
                        .multilineTextAlignment(.center)
                        .padding(.horizontal, screenWidth * 0.08)
                        .padding(.bottom, screenHeight * 0.04)
                        
                        // 用餐方式选择已移除
                        // 默认设置为堂食
                        VStack {
                            // 空白区域
                        }
                        .onAppear {
                            dataManager.selectedDiningType = .dineIn
                        }
                        .padding(.bottom, 15)
                    
                        // 电话注册区域
                        VStack(spacing: isLargeScreen ? 25 : 20) {
                            if !isCodeSent {
                                // 手机号输入
                                VStack(alignment: .center, spacing: isLargeScreen ? 15 : 12) {
                                    Text(dataManager.currentLanguage == "zh" ? AppStrings.Login.enterPhoneToRegister : AppStrings.Login.enterPhoneToRegisterEn)
                                        .font(isLargeScreen ? .headline : .subheadline)
                                        .fontWeight(.medium)
                                        .foregroundColor(.white)
                                        .multilineTextAlignment(.center)
                                    
                                    HStack(spacing: isLargeScreen ? 15 : 12) {
                                        // 电话号码输入框 - 优化交互体验
                                        VStack {
                                            HStack {
                                                Text("+65")
                                                    .foregroundColor(.white)
                                                
                                                TextField("", text: $phoneNumber)
                                                    .keyboardType(.numberPad)
                                                    .foregroundColor(.white)
                                                    .focused($phoneNumberFocused)
                                                    .placeholder(when: phoneNumber.isEmpty) {
                                                        Text("8XXXXXXX")
                                                            .foregroundColor(.gray.opacity(0.7))
                                                    }
                                                    .onChange(of: phoneNumber) { newValue in
                                                        if LoginUIConfig.enableTextFieldOptimization {
                                                            interactionManager.handleInputDebounce {
                                                                let filtered = newValue.filter { $0.isNumber }
                                                                phoneNumber = String(filtered.prefix(8))
                                                            }
                                                        } else {
                                                            let filtered = newValue.filter { $0.isNumber }
                                                            phoneNumber = String(filtered.prefix(8))
                                                        }
                                                    }
                                                    .onChange(of: phoneNumberFocused) { focused in
                                                        if focused {
                                                            // 立即更新焦点状态，优化首次响应
                                                            interactionManager.setFocus(to: .phoneNumber)
                                                            
                                                            // 异步处理触觉反馈，避免阻塞UI
                                                            if LoginUIConfig.enableFirstTapOptimization {
                                                                interactionManager.provideFeedbackAsync()
                                                            } else if LoginUIConfig.enableHapticFeedback {
                                                                interactionManager.provideFeedback()
                                                            }
                                                        }
                                                    }
                                            }
                                            .onTapGesture {
                                                // 扩大点击区域：点击整个HStack区域（包括+65标签和周围空白）都能激活输入框
                                                if LoginUIConfig.enableFirstTapOptimization {
                                                    phoneNumberFocused = true
                                                    interactionManager.setFocus(to: .phoneNumber)
                                                    interactionManager.provideFeedbackAsync()
                                                }
                                            }
                                            .padding(.vertical, 8)
                                            .padding(.horizontal, 16)
                                            .background(
                                                RoundedRectangle(cornerRadius: 12)
                                                    .fill(Color.white.opacity(0.1))
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: 12)
                                                            .stroke(
                                                                Color(red: 1.0, green: 0.6, blue: 0.2)
                                                                    .opacity(phoneNumberFocused ? LoginUIConfig.focusedBorderOpacity : LoginUIConfig.unfocusedBorderOpacity),
                                                                lineWidth: phoneNumberFocused ? 2 : 1
                                                            )
                                                            .animation(.easeInOut(duration: LoginUIConfig.borderHighlightDuration), value: phoneNumberFocused)
                                                    )
                                            )
                                        }
                                        .frame(width: isLargeScreen ? min(screenWidth * 0.45, 220) : 180)
                                        
                                        // 获取验证码按钮 - 响应式宽度
                                        Button(action: {
                                            // 优化按钮响应：异步处理触觉反馈
                                            if LoginUIConfig.enableFirstTapOptimization {
                                                interactionManager.provideFeedbackAsync()
                                                // 减少不必要的延迟，立即执行操作
                                                sendVerificationCode()
                                            } else {
                                                if LoginUIConfig.enableHapticFeedback {
                                                    interactionManager.provideFeedback()
                                                }
                                                DispatchQueue.main.asyncAfter(deadline: .now() + LoginUIConfig.buttonFeedbackDelay) {
                                                    sendVerificationCode()
                                                }
                                            }
                                        }) {
                                            HStack {
                                                if isLoading {
                                                    ProgressView()
                                                        .progressViewStyle(CircularProgressViewStyle(tint: Color(red: 0.12, green: 0.12, blue: 0.12)))
                                                        .scaleEffect(0.8)
                                                }
                                                Text(dataManager.currentLanguage == "zh" ? AppStrings.Login.getCode : AppStrings.Login.getCodeEn)
                                                    .font(isLargeScreen ? .headline : .subheadline)
                                                    .fontWeight(.semibold)
                                            }
                                            .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                                            .padding(.horizontal, isLargeScreen ? 20 : 16)
                                            .padding(.vertical, isLargeScreen ? 12 : 8)
                                            .background(
                                                RoundedRectangle(cornerRadius: 12)
                                                    .fill(
                                                        LinearGradient(
                                                            colors: [
                                                                Color(red: 1.0, green: 0.84, blue: 0.0),
                                                                Color(red: 1.0, green: 0.6, blue: 0.2)
                                                            ],
                                                            startPoint: .leading,
                                                            endPoint: .trailing
                                                        )
                                                    )
                                            )
                                        }
                                        .disabled(phoneNumber.count != 8 || isLoading)
                                        .opacity(phoneNumber.count == 8 && !isLoading ? 1.0 : 0.6)
                                        .frame(width: isLargeScreen ? min(screenWidth * 0.35, 160) : 140)
                                    }
                                    
                                    // 生物识别登录按钮 - 显示给所有曾经启用过生物识别的用户
                                    if dataManager.isBiometricAvailable() && (dataManager.currentUser?.biometricLoginEnabled == true || dataManager.hasAnyBiometricCredentials()) {
                                        Button(action: {
                                            interactionManager.switchLoginMethod()
                                            // 优化按钮响应：异步处理触觉反馈
                                            if LoginUIConfig.enableFirstTapOptimization {
                                                interactionManager.provideFeedbackAsync()
                                                // 减少不必要的延迟，立即执行操作
                                                performBiometricLogin()
                                            } else {
                                                if LoginUIConfig.enableHapticFeedback {
                                                    interactionManager.provideFeedback()
                                                }
                                                DispatchQueue.main.asyncAfter(deadline: .now() + LoginUIConfig.buttonFeedbackDelay) {
                                                    performBiometricLogin()
                                                }
                                            }
                                        }) {
                                            HStack {
                                                Image(systemName: dataManager.getBiometricType() == "Face ID" ? "faceid" : "touchid")
                                                    .font(isLargeScreen ? .title : .title2)
                                                Text(dataManager.currentLanguage == "zh" ? 
                                                     (dataManager.getBiometricType() == "Face ID" ? AppStrings.Login.faceIdLogin : AppStrings.Login.touchIdLogin) : 
                                                     "\(dataManager.getBiometricType()) \(AppStrings.Login.biometricLoginEn)")
                                                    .font(isLargeScreen ? .headline : .subheadline)
                                                    .fontWeight(.medium)
                                            }
                                            .foregroundColor(.white)
                                            .padding(.horizontal, isLargeScreen ? 20 : 16)
                                            .padding(.vertical, isLargeScreen ? 12 : 8)
                                            .background(
                                                RoundedRectangle(cornerRadius: 12)
                                                    .fill(Color.white.opacity(0.2))
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: 12)
                                                            .stroke(Color.white.opacity(0.3), lineWidth: 1)
                                                    )
                                            )
                                        }
                                        .padding(.top, 8)
                                    }
                                }
                                
                            } else {
                                // 验证码输入
                                VStack(alignment: .leading, spacing: isLargeScreen ? 15 : 12) {
                                    Text(dataManager.currentLanguage == "zh" ? AppStrings.Login.verificationCode : AppStrings.Login.verificationCodeEn)
                                        .font(isLargeScreen ? .headline : .subheadline)
                                        .fontWeight(.medium)
                                        .foregroundColor(.white)
                                    
                                    HStack {
                                        TextField("123456", text: $verificationCode)
                                            .keyboardType(.numberPad)
                                            .foregroundColor(.white)
                                            .padding(.vertical, 8)
                                            .padding(.horizontal, 16)
                                            .textContentType(.oneTimeCode)
                                            .autocorrectionDisabled()
                                            .textInputAutocapitalization(.never)
                                            .focused($verificationCodeFocused)
                                            .onTapGesture {
                                                // 立即响应点击，设置焦点
                                                if LoginUIConfig.enableFirstTapOptimization {
                                                    verificationCodeFocused = true
                                                    interactionManager.setFocus(to: .verificationCode)
                                                    interactionManager.provideFeedbackAsync()
                                                }
                                            }
                                            .onChange(of: verificationCode) { newValue in
                                                if LoginUIConfig.enableTextFieldOptimization {
                                                    interactionManager.handleInputDebounce {
                                                        let filtered = newValue.filter { $0.isNumber }
                                                        verificationCode = String(filtered.prefix(6))
                                                    }
                                                } else {
                                                    let filtered = newValue.filter { $0.isNumber }
                                                    verificationCode = String(filtered.prefix(6))
                                                }
                                            }
                                            .onChange(of: verificationCodeFocused) { focused in
                                                if focused {
                                                    // 立即更新焦点状态，优化响应
                                                    interactionManager.setFocus(to: .verificationCode)
                                                    
                                                    // 异步处理触觉反馈，避免阻塞UI
                                                    if LoginUIConfig.enableFirstTapOptimization {
                                                        interactionManager.provideFeedbackAsync()
                                                    } else if LoginUIConfig.enableHapticFeedback {
                                                        interactionManager.provideFeedback()
                                                    }
                                                }
                                            }
                                            .background(
                                                RoundedRectangle(cornerRadius: 12)
                                                    .fill(Color.white.opacity(0.1))
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: 12)
                                                            .stroke(
                                                                Color(red: 1.0, green: 0.6, blue: 0.2)
                                                                    .opacity(verificationCodeFocused ? LoginUIConfig.focusedBorderOpacity : LoginUIConfig.unfocusedBorderOpacity),
                                                                lineWidth: verificationCodeFocused ? 2 : 1
                                                            )
                                                            .animation(.easeInOut(duration: LoginUIConfig.borderHighlightDuration), value: verificationCodeFocused)
                                                    )
                                            )
                                            .frame(width: isLargeScreen ? min(screenWidth * 0.45, 240) : 200)
                                        
                                        // 登录按钮 - 响应式适配
                                        Button(action: {
                                            // 优化按钮响应：异步处理触觉反馈
                                            if LoginUIConfig.enableFirstTapOptimization {
                                                interactionManager.provideFeedbackAsync()
                                                // 减少不必要的延迟，立即执行操作
                                                login()
                                            } else {
                                                if LoginUIConfig.enableHapticFeedback {
                                                    interactionManager.provideFeedback()
                                                }
                                                DispatchQueue.main.asyncAfter(deadline: .now() + LoginUIConfig.buttonFeedbackDelay) {
                                                    login()
                                                }
                                            }
                                        }) {
                                            HStack {
                                                if isLoading {
                                                    ProgressView()
                                                        .progressViewStyle(CircularProgressViewStyle(tint: Color(red: 0.12, green: 0.12, blue: 0.12)))
                                                        .scaleEffect(0.8)
                                                }
                                                Text(dataManager.currentLanguage == "zh" ? AppStrings.Login.login : AppStrings.Login.loginEn)
                                                    .font(isLargeScreen ? .headline : .subheadline)
                                                    .fontWeight(.semibold)
                                            }
                                            .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                                            .padding(.horizontal, isLargeScreen ? 20 : 16)
                                            .padding(.vertical, isLargeScreen ? 12 : 8)
                                            .background(
                                                RoundedRectangle(cornerRadius: 12)
                                                    .fill(
                                                        LinearGradient(
                                                            colors: [
                                                                Color(red: 1.0, green: 0.84, blue: 0.0),
                                                                Color(red: 1.0, green: 0.6, blue: 0.2)
                                                            ],
                                                            startPoint: .leading,
                                                            endPoint: .trailing
                                                        )
                                                    )
                                            )
                                        }
                                        .disabled(verificationCode.count != 6 || isLoading)
                                        .opacity(verificationCode.count == 6 && !isLoading ? 1.0 : 0.6)
                                        .frame(width: isLargeScreen ? min(screenWidth * 0.35, 160) : 140)
                                    }
                                    
                                    // 邀请码输入（可选）
                                    HStack {
                                        TextField(dataManager.currentLanguage == "zh" ? AppStrings.Login.enterInviteCode : AppStrings.Login.enterInviteCodeEn, text: $inviteCode)
                                            .foregroundColor(.white)
                                            .padding(.vertical, 8)
                                            .padding(.horizontal, 16)
                                            .autocorrectionDisabled()
                                            .textInputAutocapitalization(.characters)
                                            .focused($inviteCodeFocused)
                                            .onTapGesture {
                                                // 立即响应点击，设置焦点
                                                if LoginUIConfig.enableFirstTapOptimization {
                                                    inviteCodeFocused = true
                                                    interactionManager.setFocus(to: .inviteCode)
                                                    interactionManager.provideFeedbackAsync()
                                                }
                                            }
                                            .onChange(of: inviteCode) { newValue in
                                                if LoginUIConfig.enableTextFieldOptimization {
                                                    interactionManager.handleInputDebounce {
                                                        // 限制邀请码长度和格式
                                                        let filtered = newValue.uppercased().filter { $0.isLetter || $0.isNumber }
                                                        inviteCode = String(filtered.prefix(10))
                                                    }
                                                } else {
                                                    let filtered = newValue.uppercased().filter { $0.isLetter || $0.isNumber }
                                                    inviteCode = String(filtered.prefix(10))
                                                }
                                            }
                                            .onChange(of: inviteCodeFocused) { focused in
                                                if focused {
                                                    // 立即更新焦点状态，优化响应
                                                    interactionManager.setFocus(to: .inviteCode)
                                                    
                                                    // 异步处理触觉反馈，避免阻塞UI
                                                    if LoginUIConfig.enableFirstTapOptimization {
                                                        interactionManager.provideFeedbackAsync()
                                                    } else if LoginUIConfig.enableHapticFeedback {
                                                        interactionManager.provideFeedback()
                                                    }
                                                }
                                            }
                                            .background(
                                                RoundedRectangle(cornerRadius: 12)
                                                    .fill(Color.white.opacity(0.1))
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: 12)
                                                            .stroke(
                                                                Color.white
                                                                    .opacity(inviteCodeFocused ? LoginUIConfig.focusedBorderOpacity : 0.3),
                                                                lineWidth: inviteCodeFocused ? 2 : 1
                                                            )
                                                            .animation(.easeInOut(duration: LoginUIConfig.borderHighlightDuration), value: inviteCodeFocused)
                                                    )
                                            )
                                            .frame(width: isLargeScreen ? min(screenWidth * 0.45, 240) : 200)
                                        
                                        VStack(alignment: .leading, spacing: 2) {
                                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Login.inviteCode : AppStrings.Login.inviteCodeEn)
                                                .font(isLargeScreen ? .subheadline : .caption)
                                                .fontWeight(.medium)
                                                .foregroundColor(.white.opacity(0.8))
                                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Login.optional : AppStrings.Login.optionalEn)
                                                .font(isLargeScreen ? .caption : .caption2)
                                                .fontWeight(.light)
                                                .foregroundColor(.white.opacity(0.6))
                                        }
                                        .frame(width: isLargeScreen ? min(screenWidth * 0.35, 160) : 140)
                                    }
                                    .padding(.top, 8)
                                }
                                
                                // 重新发送验证码
                                Button(action: {
                                    if LoginUIConfig.enableHapticFeedback {
                                        interactionManager.provideFeedback()
                                    }
                                    DispatchQueue.main.asyncAfter(deadline: .now() + LoginUIConfig.buttonFeedbackDelay) {
                                        resendCode()
                                    }
                                }) {
                                    Text(canResendCode ? 
                                         (dataManager.currentLanguage == "zh" ? AppStrings.Login.resendCode : AppStrings.Login.resendCodeEn) :
                                         "\(countdown)s")
                                        .font(isLargeScreen ? .headline : .subheadline)
                                        .foregroundColor(canResendCode ? Color(red: 1.0, green: 0.6, blue: 0.2) : .gray)
                                }
                                .disabled(!canResendCode)
                            }
                        }
                        .padding(.horizontal, screenWidth * 0.08)
                        .padding(.bottom, screenHeight * 0.025)
                        
                        // 第三方登录
                        VStack(spacing: isLargeScreen ? 20 : 15) {
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Login.orSignInWith : AppStrings.Login.orSignInWithEn)
                                .font(isLargeScreen ? .headline : .subheadline)
                                .foregroundColor(.gray)
                            
                            HStack(spacing: isLargeScreen ? 40 : 30) {
                                // Apple登录 - 大师级3D立体设计
                                Button(action: {
                                    interactionManager.switchLoginMethod()
                                    // 优化按钮响应：异步处理触觉反馈
                                    if LoginUIConfig.enableFirstTapOptimization {
                                        interactionManager.provideFeedbackAsync()
                                    } else if LoginUIConfig.enableHapticFeedback {
                                        interactionManager.provideFeedback()
                                    }
                                    // Apple登录逻辑
                                }) {
                                    ZStack {
                                        // 外层阴影
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 20 : 18)
                                            .fill(Color.black.opacity(0.3))
                                            .frame(width: isLargeScreen ? 64 : 54, height: isLargeScreen ? 64 : 54)
                                            .offset(x: 2, y: 4)
                                        
                                        // 主体渐变背景
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 18 : 16)
                                            .fill(
                                                LinearGradient(
                                                    colors: [
                                                        Color(red: 0.98, green: 0.98, blue: 1.0),
                                                        Color(red: 0.88, green: 0.88, blue: 0.92),
                                                        Color(red: 0.75, green: 0.75, blue: 0.80)
                                                    ],
                                                    startPoint: .topLeading,
                                                    endPoint: .bottomTrailing
                                                )
                                            )
                                            .frame(width: isLargeScreen ? 60 : 50, height: isLargeScreen ? 60 : 50)
                                        
                                        // 内层高光
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 18 : 16)
                                            .stroke(
                                                LinearGradient(
                                                    colors: [
                                                        Color.white.opacity(0.8),
                                                        Color.clear
                                                    ],
                                                    startPoint: .topLeading,
                                                    endPoint: .bottomTrailing
                                                ),
                                                lineWidth: 1
                                            )
                                            .frame(width: isLargeScreen ? 60 : 50, height: isLargeScreen ? 60 : 50)
                                        
                                        // 外层边框
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 18 : 16)
                                            .stroke(
                                                LinearGradient(
                                                    colors: [
                                                        Color(red: 0.6, green: 0.6, blue: 0.65),
                                                        Color(red: 0.4, green: 0.4, blue: 0.45)
                                                    ],
                                                    startPoint: .topLeading,
                                                    endPoint: .bottomTrailing
                                                ),
                                                lineWidth: 1.5
                                            )
                                            .frame(width: isLargeScreen ? 60 : 50, height: isLargeScreen ? 60 : 50)
                                        
                                        // Apple logo with 3D effect
                                        ZStack {
                                            // 阴影层
                                            Image(systemName: "applelogo")
                                                .font(.system(size: isLargeScreen ? 30 : 26, weight: .medium))
                                                .foregroundColor(Color.black.opacity(0.3))
                                                .offset(x: 1, y: 1)
                                            
                                            // 主体logo
                                            Image(systemName: "applelogo")
                                                .font(.system(size: isLargeScreen ? 30 : 26, weight: .medium))
                                                .foregroundColor(Color(red: 0.1, green: 0.1, blue: 0.1))
                                        }
                                    }
                                }
                                
                                // Google登录 - 大师级3D立体设计
                                Button(action: {
                                    interactionManager.switchLoginMethod()
                                    // 优化按钮响应：异步处理触觉反馈
                                    if LoginUIConfig.enableFirstTapOptimization {
                                        interactionManager.provideFeedbackAsync()
                                    } else if LoginUIConfig.enableHapticFeedback {
                                        interactionManager.provideFeedback()
                                    }
                                    // Google登录逻辑
                                }) {
                                    ZStack {
                                        // 外层阴影
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 20 : 18)
                                            .fill(Color.black.opacity(0.2))
                                            .frame(width: isLargeScreen ? 64 : 54, height: isLargeScreen ? 64 : 54)
                                            .offset(x: 2, y: 4)
                                        
                                        // 主体背景
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 18 : 16)
                                            .fill(
                                                LinearGradient(
                                                    colors: [
                                                        Color.white,
                                                        Color(red: 0.96, green: 0.96, blue: 0.96),
                                                        Color(red: 0.92, green: 0.92, blue: 0.92)
                                                    ],
                                                    startPoint: .topLeading,
                                                    endPoint: .bottomTrailing
                                                )
                                            )
                                            .frame(width: isLargeScreen ? 60 : 50, height: isLargeScreen ? 60 : 50)
                                        
                                        // 内层高光
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 18 : 16)
                                            .stroke(
                                                LinearGradient(
                                                    colors: [
                                                        Color.white,
                                                        Color.clear
                                                    ],
                                                    startPoint: .topLeading,
                                                    endPoint: .bottomTrailing
                                                ),
                                                lineWidth: 1
                                            )
                                            .frame(width: isLargeScreen ? 60 : 50, height: isLargeScreen ? 60 : 50)
                                        
                                        // 外层边框
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 18 : 16)
                                            .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                                            .frame(width: isLargeScreen ? 60 : 50, height: isLargeScreen ? 60 : 50)
                                        
                                        // Google G logo with 3D effect
                                        ZStack {
                                            // 外层阴影圆
                                            Circle()
                                                .fill(Color.black.opacity(0.1))
                                                .frame(width: isLargeScreen ? 36 : 30, height: isLargeScreen ? 36 : 30)
                                                .offset(x: 1, y: 1)
                                            
                                            // 主体彩色圆
                                            Circle()
                                                .fill(
                                                    RadialGradient(
                                                        colors: [
                                                            Color(red: 0.26, green: 0.52, blue: 0.96),
                                                            Color(red: 0.85, green: 0.26, blue: 0.21),
                                                            Color(red: 0.98, green: 0.74, blue: 0.02),
                                                            Color(red: 0.00, green: 0.65, blue: 0.31)
                                                        ],
                                                        center: .topLeading,
                                                        startRadius: isLargeScreen ? 6 : 5,
                                                        endRadius: isLargeScreen ? 24 : 20
                                                    )
                                                )
                                                .frame(width: isLargeScreen ? 34 : 28, height: isLargeScreen ? 34 : 28)
                                            
                                            // 内层高光
                                            Circle()
                                                .stroke(
                                                    LinearGradient(
                                                        colors: [
                                                            Color.white.opacity(0.6),
                                                            Color.clear
                                                        ],
                                                        startPoint: .topLeading,
                                                        endPoint: .bottomTrailing
                                                    ),
                                                    lineWidth: 1
                                                )
                                                .frame(width: isLargeScreen ? 34 : 28, height: isLargeScreen ? 34 : 28)
                                            
                                            // G字母阴影
                                            Text("G")
                                                .font(.system(size: isLargeScreen ? 19 : 16, weight: .bold, design: .rounded))
                                                .foregroundColor(Color.black.opacity(0.3))
                                                .offset(x: 0.5, y: 0.5)
                                            
                                            // G字母主体
                                            Text("G")
                                                .font(.system(size: isLargeScreen ? 19 : 16, weight: .bold, design: .rounded))
                                                .foregroundColor(.white)
                                        }
                                    }
                                }
                                
                                // 微信登录 - 大师级3D立体设计
                                Button(action: {
                                    interactionManager.switchLoginMethod()
                                    if LoginUIConfig.enableHapticFeedback {
                                        interactionManager.provideFeedback()
                                    }
                                    // 微信登录逻辑
                                }) {
                                    ZStack {
                                        // 外层阴影
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 20 : 18)
                                            .fill(Color.black.opacity(0.3))
                                            .frame(width: isLargeScreen ? 64 : 54, height: isLargeScreen ? 64 : 54)
                                            .offset(x: 2, y: 4)
                                        
                                        // 主体渐变背景
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 18 : 16)
                                            .fill(
                                                LinearGradient(
                                                    colors: [
                                                        Color(red: 0.50, green: 0.85, blue: 0.28),
                                                        Color(red: 0.44, green: 0.78, blue: 0.22),
                                                        Color(red: 0.35, green: 0.65, blue: 0.18)
                                                    ],
                                                    startPoint: .topLeading,
                                                    endPoint: .bottomTrailing
                                                )
                                            )
                                            .frame(width: isLargeScreen ? 60 : 50, height: isLargeScreen ? 60 : 50)
                                        
                                        // 内层高光
                                        RoundedRectangle(cornerRadius: isLargeScreen ? 18 : 16)
                                            .stroke(
                                                LinearGradient(
                                                    colors: [
                                                        Color.white.opacity(0.6),
                                                        Color.clear
                                                    ],
                                                    startPoint: .topLeading,
                                                    endPoint: .bottomTrailing
                                                ),
                                                lineWidth: 1
                                            )
                                            .frame(width: isLargeScreen ? 60 : 50, height: isLargeScreen ? 60 : 50)
                                        
                                        // 微信图标3D效果
                                        ZStack {
                                            // 主要对话气泡阴影
                                            RoundedRectangle(cornerRadius: isLargeScreen ? 9 : 8)
                                                .fill(Color.black.opacity(0.2))
                                                .frame(width: isLargeScreen ? 21 : 18, height: isLargeScreen ? 14 : 12)
                                                .offset(x: -2.5, y: -1.5)
                                            
                                            // 主要对话气泡
                                            RoundedRectangle(cornerRadius: isLargeScreen ? 9 : 8)
                                                .fill(
                                                    LinearGradient(
                                                        colors: [
                                                            Color.white,
                                                            Color(red: 0.95, green: 0.95, blue: 0.95)
                                                        ],
                                                        startPoint: .topLeading,
                                                        endPoint: .bottomTrailing
                                                    )
                                                )
                                                .frame(width: isLargeScreen ? 21 : 18, height: isLargeScreen ? 14 : 12)
                                                .offset(x: -3, y: -2)
                                            
                                            // 次要对话气泡阴影
                                            RoundedRectangle(cornerRadius: isLargeScreen ? 7 : 6)
                                                .fill(Color.black.opacity(0.15))
                                                .frame(width: isLargeScreen ? 16 : 14, height: isLargeScreen ? 12 : 10)
                                                .offset(x: 4.5, y: 3.5)
                                            
                                            // 次要对话气泡
                                            RoundedRectangle(cornerRadius: isLargeScreen ? 7 : 6)
                                                .fill(
                                                    LinearGradient(
                                                        colors: [
                                                            Color.white.opacity(0.95),
                                                            Color(red: 0.92, green: 0.92, blue: 0.92)
                                                        ],
                                                        startPoint: .topLeading,
                                                        endPoint: .bottomTrailing
                                                    )
                                                )
                                                .frame(width: isLargeScreen ? 16 : 14, height: isLargeScreen ? 12 : 10)
                                                .offset(x: 4, y: 3)
                                            
                                            // 小尾巴装饰阴影
                                            Circle()
                                                .fill(Color.black.opacity(0.2))
                                                .frame(width: isLargeScreen ? 5 : 4, height: isLargeScreen ? 5 : 4)
                                                .offset(x: -7.5, y: 2.5)
                                            
                                            // 小尾巴装饰
                                            Circle()
                                                .fill(Color.white)
                                                .frame(width: isLargeScreen ? 5 : 4, height: isLargeScreen ? 5 : 4)
                                                .offset(x: -8, y: 2)
                                            
                                            // 小尾巴装饰2阴影
                                            Circle()
                                                .fill(Color.black.opacity(0.15))
                                                .frame(width: isLargeScreen ? 4 : 3, height: isLargeScreen ? 4 : 3)
                                                .offset(x: 9.5, y: 7.5)
                                            
                                            // 小尾巴装饰2
                                            Circle()
                                                .fill(Color.white.opacity(0.9))
                                                .frame(width: isLargeScreen ? 4 : 3, height: isLargeScreen ? 4 : 3)
                                                .offset(x: 9, y: 7)
                                        }
                                    }
                                }
                            }
                        }
                        .padding(.horizontal, screenWidth * 0.08)
                        .padding(.bottom, screenHeight * 0.035)
                        
                        // 游客模式
                        Button(action: {
                            interactionManager.switchLoginMethod()
                            // 优化按钮响应：异步处理触觉反馈
                            if LoginUIConfig.enableFirstTapOptimization {
                                interactionManager.provideFeedbackAsync()
                                // 减少不必要的延迟，立即执行操作
                                loginAsGuest()
                            } else {
                                if LoginUIConfig.enableHapticFeedback {
                                    interactionManager.provideFeedback()
                                }
                                DispatchQueue.main.asyncAfter(deadline: .now() + LoginUIConfig.buttonFeedbackDelay) {
                                    loginAsGuest()
                                }
                            }
                        }) {
                            Text(dataManager.currentLanguage == "zh" ? "游客模式" : "Guest Mode")
                                .font(isLargeScreen ? .headline : .subheadline)
                                .fontWeight(.medium)
                                .foregroundColor(.white)
                                .underline()
                        }
                        .padding(.bottom, screenHeight * 0.035)
                        
                        // 语言选择
                        Button(action: { showingLanguageSelector = true }) {
                            HStack {
                                Image(systemName: "globe")
                                Text(dataManager.currentLanguage == "zh" ? "English" : "中文")
                            }
                            .font(isLargeScreen ? .headline : .subheadline)
                            .foregroundColor(Color(red: 1.0, green: 0.9, blue: 0.7))
                        }
                        .padding(.bottom, screenHeight * 0.035)
                        
                        // 协议链接
                        VStack(spacing: isLargeScreen ? 10 : 8) {
                            Text(dataManager.currentLanguage == "zh" ? "继续即表示您同意我们的" : "By continuing, you agree to our")
                                .font(isLargeScreen ? .subheadline : .caption)
                                .foregroundColor(.gray)
                                .multilineTextAlignment(.center)
                            
                            HStack(spacing: isLargeScreen ? 8 : 5) {
                                Button(action: { showingTerms = true }) {
                                    Text(dataManager.currentLanguage == "zh" ? "服务条款" : "Terms of Service")
                                        .font(isLargeScreen ? .subheadline : .caption)
                                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                                        .underline()
                                }
                                
                                Text(dataManager.currentLanguage == "zh" ? "和" : "and")
                                    .font(isLargeScreen ? .subheadline : .caption)
                                    .foregroundColor(.gray)
                                
                                Button(action: { showingPrivacy = true }) {
                                    Text(dataManager.currentLanguage == "zh" ? "隐私政策" : "Privacy Policy")
                                        .font(isLargeScreen ? .subheadline : .caption)
                                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                                        .underline()
                                }
                            }
                        }
                        .padding(.horizontal, screenWidth * 0.08)
                        .padding(.bottom, screenHeight * 0.035)
                        
                        Spacer()
                        
                        // 版权信息 - 添加隐藏诊断入口
                        Text("© 2025 Cu Mr Bull Pte. Ltd.")
                            .font(isLargeScreen ? .subheadline : .caption)
                            .foregroundColor(.gray)
                            .padding(.bottom, isLargeScreen ? screenHeight * 0.06 : screenHeight * 0.035)
                            .onTapGesture {
                                diagnosticTapCount += 1
                                if diagnosticTapCount >= 5 {
                                    showDiagnostic = true
                                    diagnosticTapCount = 0
                                }
                                
                                // 5秒后重置计数
                                DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                                    diagnosticTapCount = 0
                                }
                            }
                            .onLongPressGesture(minimumDuration: 2.0) {
                                showPerformanceTest = true
                            }
                    }
                }
            }
        }
        .alert(isPresented: $showingAlert) {
            Alert(
                title: Text(dataManager.currentLanguage == "zh" ? "提示" : "Notice"),
                message: Text(alertMessage),
                dismissButton: .default(Text("OK"))
            )
        }
        .sheet(isPresented: $showingTerms) {
            // 服务条款页面
            NavigationView {
                ScrollView(.vertical, showsIndicators: false) {
                    VStack(alignment: .leading, spacing: 20) {
                        VStack(alignment: .leading, spacing: 15) {
    Text(dataManager.currentLanguage == "zh" ? "服务条款" : "Terms of Service")
        .font(.title2)
        .fontWeight(.bold)
        .foregroundColor(.black)
    
    Text(dataManager.currentLanguage == "zh" ? "最后更新日期：2025年7月" : "Last Updated: July 2025")
        .font(.subheadline)
        .foregroundColor(.gray)
    
    Text(dataManager.currentLanguage == "zh" ? "欢迎使用 Cu Mr Bull 点餐应用。本条款规范您与 Cu Mr Bull Pte Ltd 之间的法律关系与权利义务。请在使用本 App 前仔细阅读并同意以下条款。" : "Welcome to the Cu Mr Bull ordering app. These Terms of Service govern the legal relationship between you and Cu Mr Bull Pte Ltd. Please read and agree to the following terms before using our app.")
        .font(.system(size: 12))
        .foregroundColor(.black)
    
    Text(dataManager.currentLanguage == "zh" ? "1. 使用资格" : "1. Eligibility")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["用户须为年满18岁、具备民事行为能力者。", "注册账号即视为您同意受本条款约束。"] : ["Users must be at least 18 years old and legally competent.", "By registering an account, you agree to be bound by these terms."], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "2. 价格与付款" : "2. Pricing & Payment")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["所有价格均以新币（SGD）计价。", "商品价格是否含 GST（商品及服务税）以界面标注为准。", "支持的支付方式包括信用卡、Apple Pay、Google Pay、PayNow 等。"] : ["All prices are listed in Singapore Dollars (SGD).", "Whether GST (Goods and Services Tax) is included will be indicated on the interface.", "We accept payment via credit cards, Apple Pay, Google Pay, PayNow, and other listed methods."], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "3. 订单与取消" : "3. Orders & Cancellations")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["所有订单提交后即进入备餐流程，不接受因个人原因取消。", "若订单发生错误、食物严重不符或卫生问题，请立即联系客服，我们将视情况处理退款或更换。", "请于预计取餐时间 15 分钟内完成自取，超时可能影响食品品质。"] : ["Once submitted, orders immediately enter preparation and cannot be canceled due to personal reasons.", "In the case of order errors, severe food discrepancies, or hygiene issues, please contact customer service immediately - refunds or replacements may be granted based on the situation.", "Please collect your order within 15 minutes of the scheduled pickup time. Late pickups may affect food quality."], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "4. 优惠与促销" : "4. Promotions & Discounts")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["所有优惠码与会员积分不可兑换现金，使用有效期与条件请参阅具体活动规则。", "商家有权在不通知的情况下修改或终止任何促销活动。"] : ["All promo codes and reward points are non-cashable. Terms and validity of each promotion are governed by the specific campaign.", "Cu Mr Bull reserves the right to change or terminate any promotion without prior notice."], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "5. 退款政策" : "5. Refund Policy")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["本应用仅在以下情况支持退款：", "订单错误或食物严重与描述不符", "食品存在明显质量或健康安全问题", "不因口味喜好、误操作、临时变更而退款。", "退款将在确认后7个工作日内原路退回。", "含有优惠折扣订单，仅退还实际支付金额。"] : ["Refunds are only applicable under the following circumstances:", "Incorrect orders or severe mismatches in food", "Food quality issues or potential health and safety risks", "Refunds will not be granted for taste preferences, mistaken orders, or last-minute changes.", "Refunds will be processed within 7 business days via the original payment method.", "For discounted orders, the refunded amount will be based on the actual paid value after discounts."], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "6. 知识产权" : "6. Intellectual Property")
        .font(.headline)
        .foregroundColor(.black)
    Text(dataManager.currentLanguage == "zh" ? "本应用界面、内容、图像及商标均归 Cu Mr Bull 所有。未经书面许可，不得复制、传播、改作或用于商业用途。" : "All content, images, UI design, and trademarks in this App belong to Cu Mr Bull. No part of the App may be copied, distributed, modified, or used commercially without written permission.")
        .font(.system(size: 12))
        .foregroundColor(.black)
    
    Text(dataManager.currentLanguage == "zh" ? "7. 责任限制" : "7. Limitation of Liability")
        .font(.headline)
        .foregroundColor(.black)
    Text(dataManager.currentLanguage == "zh" ? "在法律允许范围内，Cu Mr Bull 对于因网络中断、不可抗力或第三方系统故障导致的订单延迟、支付失败等不承担任何赔偿责任。" : "To the extent permitted by law, Cu Mr Bull is not liable for any delay in order, payment failure, or service interruption caused by network issues, force majeure, or third-party system failures.")
        .font(.system(size: 12))
        .foregroundColor(.black)
    
    Text(dataManager.currentLanguage == "zh" ? "8. 条款修改与终止" : "8. Changes & Termination")
        .font(.headline)
        .foregroundColor(.black)
    Text(dataManager.currentLanguage == "zh" ? "我们保留随时更新本条款的权利，修改将在 App 中展示。用户持续使用视为同意更新内容。\n\n如您对本条款有疑问，欢迎联系：info@cumrbull.com.sg" : "We reserve the right to amend these Terms at any time. Any updates will be displayed in the App. Continued use of the App after such updates will constitute your acceptance of the revised terms.\n\nFor any questions regarding these terms, please contact: info@cumrbull.com.sg")
        .font(.system(size: 12))
        .foregroundColor(.black)
}
.padding(20)
                    }
                }
                .navigationTitle(dataManager.currentLanguage == "zh" ? "服务条款" : "Terms of Service")
                .navigationBarTitleDisplayMode(.inline)
                .navigationBarItems(trailing: Button("Done") {
                    showingTerms = false
                })
            }
        }
        .sheet(isPresented: $showingPrivacy) {
            // 隐私政策页面
            NavigationView {
                ScrollView(.vertical, showsIndicators: false) {
                    VStack(alignment: .leading, spacing: 20) {
                        VStack(alignment: .leading, spacing: 15) {
    Text(dataManager.currentLanguage == "zh" ? "Cu Mr Bull 隐私政策" : "Cu Mr Bull Privacy Policy")
        .font(.title2)
        .fontWeight(.bold)
        .foregroundColor(.black)
    
    Text(dataManager.currentLanguage == "zh" ? "最后更新日期：2025年7月" : "Last Updated: July 2025")
        .font(.subheadline)
        .foregroundColor(.gray)
    
    Text(dataManager.currentLanguage == "zh" ? "本隐私政策旨在说明 Cu Mr Bull Pte Ltd（以下简称\"我们\"）如何收集、使用、披露和保护您的个人资料。我们致力于遵守新加坡《个人资料保护法》（PDPA）相关规定，并保障您的信息安全。" : "This Privacy Policy outlines how Cu Mr Bull Pte Ltd (\"we\", \"our\", or \"us\") collects, uses, discloses, and protects your personal data. We are committed to complying with the Personal Data Protection Act (PDPA) of Singapore and ensuring your data is safe.")
        .font(.system(size: 12))
        .foregroundColor(.black)
    
    Text(dataManager.currentLanguage == "zh" ? "1. 收集的信息" : "1. Information We Collect")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["姓名、手机号、电子邮箱", "订单信息、支付方式、交易记录", "App 使用行为（包括设备信息、浏览行为）", "与我们沟通的记录（如客服聊天、反馈表单）"] : ["Name, mobile number, and email address", "Order details, payment method, and transaction records", "App usage behavior (including device information and browsing patterns)", "Communication records with us (e.g., live chat, feedback forms)"], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "2. 使用方式" : "2. How We Use Your Data")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["处理订单、自取通知、付款确认", "推送优惠活动、会员奖励、节日促销", "改进产品与服务（包括用户界面与推荐菜单）", "遵守法律义务及税务记录"] : ["Processing orders, self-pickup notifications, and payment confirmations", "Sending promotions, member rewards, and seasonal offers", "Improving our products and services (including UI and menu recommendations)", "Fulfilling legal and tax-related obligations"], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "3. 第三方共享" : "3. Data Sharing with Third Parties")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["支付平台（如 Stripe、Apple Pay、PayNow、Google Pay）", "营销通讯平台（如 WhatsApp Business、SMS、电子邮件）", "数据托管与分析服务（如 Firebase、Google Analytics）"] : ["Payment platforms (e.g., Stripe, Apple Pay, PayNow, Google Pay)", "Marketing communication platforms (e.g., WhatsApp Business, SMS, email)", "Hosting and analytics services (e.g., Firebase, Google Analytics)"], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    Text(dataManager.currentLanguage == "zh" ? "我们承诺仅在业务必要范围内共享信息，并确保合作方遵守数据保护责任。" : "We ensure that shared data is limited to business needs and that all third parties are contractually obligated to protect your data.")
        .font(.system(size: 12))
        .foregroundColor(.black)
    
    Text(dataManager.currentLanguage == "zh" ? "4. 您的权利" : "4. Your Rights")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["查询或请求访问我们持有的您的个人资料", "请求更正错误信息", "请求撤销同意接收营销信息（点击退订链接或联系客服）"] : ["Request access to your personal data we hold", "Request correction of inaccurate information", "Withdraw consent for marketing communications (via unsubscribe link or by contacting us)"], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "5. 数据保护措施" : "5. Data Protection Measures")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["加密传输与存储", "访问权限限制与内部培训", "防火墙与安全备份机制"] : ["Secure transmission and encrypted storage", "Access control and staff training", "Firewalls and backup systems"], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "6. 数据保留期限" : "6. Data Retention")
        .font(.headline)
        .foregroundColor(.black)
    ForEach(dataManager.currentLanguage == "zh" ? ["法律或税务规定的时限期满，或", "您注销账户后最长12个月"] : ["The legal or tax-related retention period ends, or", "Up to 12 months after you deactivate your account"], id: \.self) { item in
        Text("• " + item)
            .font(.system(size: 12))
            .foregroundColor(.black)
    }
    
    Text(dataManager.currentLanguage == "zh" ? "7. 隐私政策更新" : "7. Updates to Privacy Policy")
        .font(.headline)
        .foregroundColor(.black)
    Text(dataManager.currentLanguage == "zh" ? "我们保留不经事先通知随时修改本政策的权利。修改后将更新版本日期，并通过 App 通知用户。\n\n如对隐私政策有任何疑问，请联系 info@cumrbull.com.sg。" : "We reserve the right to update this policy without prior notice. Any changes will be reflected with a new \"Last Updated\" date and notified through the App.\n\nFor any questions, please contact us at: info@cumrbull.com.sg")
        .font(.system(size: 12))
        .foregroundColor(.black)
}
.padding(20)
                    }
                }
                .navigationTitle(dataManager.currentLanguage == "zh" ? "隐私政策" : "Privacy Policy")
                .navigationBarTitleDisplayMode(.inline)
                .navigationBarItems(trailing: Button("Done") {
                    showingPrivacy = false
                })
            }
        }
        .actionSheet(isPresented: $showingLanguageSelector) {
            ActionSheet(
                title: Text(dataManager.currentLanguage == "zh" ? "选择语言" : "Select Language"),
                buttons: [
                    .default(Text("中文")) {
                        if dataManager.currentLanguage != "zh" {
                            dataManager.switchLanguage()
                        }
                    },
                    .default(Text("English")) {
                        if dataManager.currentLanguage != "en" {
                            dataManager.switchLanguage()
                        }
                    },
                    .cancel()
                ]
            )
        }
        .onDisappear {
            timer?.invalidate()
            timer = nil
        }
        .onAppear {
            // 尝试自动登录
            if !biometricLoginAttempted {
                biometricLoginAttempted = true
                tryAutoLogin()
            }
        }
        .sheet(isPresented: $showingBiometricPrompt) {
            BiometricPromptView(onLoginComplete: {
                // BiometricPromptView完成后关闭LoginView
                dismiss()
            })
            .environmentObject(dataManager)
        }
        .sheet(isPresented: $showDiagnostic) {
            LoginPerformanceDiagnosticView()
        }
        .sheet(isPresented: $showPerformanceTest) {
            LoginPerformanceTestView()
        }
    }
    
    private func sendVerificationCode() {
        // 验证手机号格式：8位数字且以8或9开头
        guard phoneNumber.count == 8, 
              phoneNumber.allSatisfy({ $0.isNumber }),
              phoneNumber.first == "8" || phoneNumber.first == "9" else {
            alertMessage = dataManager.currentLanguage == "zh" ? "请输入正确的电话号码" : "Please enter a correct phone number"
            showingAlert = true
            return
        }
        
        isLoading = true
        
        // 模拟网络延迟
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            isLoading = false
            isCodeSent = true
            startCountdown()
        }
    }
    
    private func login() {
        isLoading = true
        
        // 模拟网络延迟
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            isLoading = false
            
            // 使用新的登录方法，支持邀请码
            let inviteCodeToUse = inviteCode.isEmpty ? nil : inviteCode
            if dataManager.loginUser(phoneNumber: phoneNumber, verificationCode: verificationCode, inviteCode: inviteCodeToUse) {
                // 登录成功，检查是否需要显示生物识别设置
                let isBiometricAvailable = dataManager.isBiometricAvailable()
                let biometricEnabled = dataManager.currentUser?.biometricLoginEnabled ?? false
                
                // 调试日志：帮助诊断生物识别页面跳过问题
                if AppConfig.enableDebugLogging {
                    print("[BiometricDebug] 登录成功后检查:")
                    print("[BiometricDebug] - 设备支持生物识别: \(isBiometricAvailable)")
                    print("[BiometricDebug] - 用户已启用生物识别: \(biometricEnabled)")
                    print("[BiometricDebug] - 用户ID: \(dataManager.currentUser?.id.uuidString ?? "nil")")
                    print("[BiometricDebug] - 会显示生物识别提示: \(isBiometricAvailable && !biometricEnabled)")
                }
                
                // 只有在设备支持且用户未启用生物识别时才显示提示界面
                if isBiometricAvailable && !biometricEnabled {
                    // 添加延迟确保界面能够正常显示
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        self.showingBiometricPrompt = true
                        if AppConfig.enableDebugLogging {
                            print("[BiometricDebug] 显示生物识别设置提示界面")
                        }
                    }
                } else {
                    if AppConfig.enableDebugLogging {
                        print("[BiometricDebug] 跳过生物识别提示 - 设备不支持或用户已启用")
                    }
                    dismiss()
                }
            } else {
                alertMessage = dataManager.currentLanguage == "zh" ? "验证码错误，请重试" : "Invalid verification code, please try again"
                showingAlert = true
            }
        }
    }
    
    private func performBiometricLogin() {
        if AppConfig.enableDebugLogging {
            print("[DEBUG] LoginView.performBiometricLogin() - 开始生物识别登录")
        }
        
        // 安全检查：确保生物识别功能可用
        guard dataManager.isBiometricAvailable() else {
            if AppConfig.enableDebugLogging {
                print("[DEBUG] LoginView.performBiometricLogin() - 失败：生物识别功能不可用")
            }
            DispatchQueue.main.async {
                self.alertMessage = self.dataManager.currentLanguage == "zh" ? "生物识别功能不可用" : "Biometric authentication not available"
                self.showingAlert = true
            }
            return
        }
        
        // 获取启用了生物识别的用户列表
        let biometricUsers = dataManager.getBiometricEnabledUsers()
        
        // 调试日志已移除
        
        guard !biometricUsers.isEmpty else {
            // 调试日志已移除
            DispatchQueue.main.async {
                self.alertMessage = self.dataManager.currentLanguage == "zh" ? "没有找到启用生物识别的用户" : "No biometric-enabled users found"
                self.showingAlert = true
            }
            return
        }
        
        // 如果只有一个用户，直接登录
        if biometricUsers.count == 1 {
            let user = biometricUsers[0]
            loginWithBiometricUser(user)
        } else {
            // 多个用户时，使用第一个用户（可以后续改进为显示选择界面）
            let user = biometricUsers[0]
            loginWithBiometricUser(user)
        }
    }
    
    private func loginWithBiometricUser(_ user: User) {
        // 调试日志已移除
        
        // 安全检查：确保用户启用了生物识别
        guard user.biometricLoginEnabled else {
            // 调试日志已移除
            DispatchQueue.main.async {
                self.alertMessage = self.dataManager.currentLanguage == "zh" ? "该用户未启用生物识别登录" : "Biometric login not enabled for this user"
                self.showingAlert = true
            }
            return
        }
        
        // 再次确认生物识别功能可用
        guard dataManager.isBiometricAvailable() else {
            // 调试日志已移除
            DispatchQueue.main.async {
                self.alertMessage = self.dataManager.currentLanguage == "zh" ? "生物识别功能不可用" : "Biometric authentication not available"
                self.showingAlert = true
            }
            return
        }
        
        // 临时设置当前用户以便生物识别验证
        let originalUser = dataManager.currentUser
        dataManager.currentUser = user
        
        // 添加错误处理包装
        dataManager.tryBiometricLogin { success in
            
            DispatchQueue.main.async {
                if success {
                    // 调试日志已移除
                    // 确保在主线程上执行dismiss
                    self.dismiss()
                } else {
                    // 调试日志已移除
                    // 恢复原始用户状态
                    self.dataManager.currentUser = originalUser
                    self.alertMessage = self.dataManager.currentLanguage == "zh" ? "生物识别验证失败" : "Biometric authentication failed"
                    self.showingAlert = true
                }
            }
        }
    }
    
    private func tryAutoLogin() {
        let success = dataManager.tryAutoLogin()
        if success {
            dismiss()
        }
    }
    
    private func loginAsGuest() {
        dataManager.loginAsGuest()
        dismiss()
    }
    
    private func resendCode() {
        guard canResendCode else { return }
        
        isCodeSent = false
        verificationCode = ""
        sendVerificationCode()
    }
    
    private func startCountdown() {
        canResendCode = false
        countdown = 60
        
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
            countdown -= 1
            if countdown <= 0 {
                canResendCode = true
                timer?.invalidate()
                timer = nil
            }
        }
    }
}

#Preview {
    LoginView()
        .environmentObject(DataManager.shared)
}